<?php namespace system\model;
use houdunwang\model\Model;
class Category extends Model{
	//数据表
	protected $table = "category";

	//允许填充字段
	protected $allowFill = ['*' ];


	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
		['cname','isnull','分类名称不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['ctitle','isnull','分类标题不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['cdes','isnull','分类描述不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['ckeywords','isnull','分类关键字不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['csort','isnull','分类排序不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
	];

	/**
	 * 执行添加
	 */
	public function store()
	{
		//执行添加成功的时候，返回自增id，注意$allowFill需要填写
		//form表单name跟数据库保持一致
		//$res = $this->save($_POST);
		return  $this->save($_POST);
		//p($res);die;
	}
	/**
	 * 获取除了自己以及自己子集的方法
	 */
	public function getCateData($cid)
	{
		//p(Db::table('category')->get());
		//p($cid);
		//1.找当前数据的子集
		$data = Db::table('category')->get();
		$cids = $this->getSon($data,$cid);
		//p($cids);
		//2.把自己追加进去
		$cids[] = $cid;
		//3.找到除了自己和自己子集之外的数据
		$data = $this->whereNotIn('cid',$cids)->get()->toArray();
		return Arr::tree($data,'cname');
		//p($data);
	}

	/**
	 * 找自己
	 * @param $data	数组数据
	 * @param $cid	寻找哪一个分类的自己，当前分类cid
	 */
	public function getSon($data,$cid)
	{
		static $temp = [];
		foreach($data as $k=>$v)
		{
			if($v['pid']==$cid){
				$temp[] = $v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}
	/**
	 * 编辑分类
	 *
	 */
	public function edit()
	{

		//p($_POST);die;
//$model->where('id', '>', 100)->update(['cid' => 2]);
		//方式一
		/*$data = [
			'cname'=>$_POST['cname'],
			'ctitle'=>$_POST['ctitle'],
			'cdes'=>$_POST['cdes'],
			'ckeywords'=>$_POST['ckeywords'],
			'csort'=>$_POST['csort'],
			'pid'=>$_POST['pid']
		];
		$res = $this->where('cid', '=', $_POST['cid'])->update($data);
		var_dump($res);die;*/
		//方式二，采用这种方式
		$model = $this->find($_POST['cid']); // 查找主键为1的数据
		$model->cname = $_POST['cname'];
		$model->ctitle = $_POST['ctitle'];
		$model->cdes = $_POST['cdes'];
		$model->ckeywords = $_POST['ckeywords'];
		$model->csort = $_POST['csort'];
		$model->pid = $_POST['pid'];
		return $model->save(); // 保存当前数据对象

	}




















}